from sanic import Sanic
from sanic_openapi import openapi3_blueprint
from sanic.response import HTTPResponse, empty,html,file,redirect,json, text
from sanic.request import Request
from server.clock import Clock




app=Sanic('tomato_clock')
app.blueprint(openapi3_blueprint)
app.static('/static','./web')

clock=Clock()

app.ctx.clock=clock


@app.get('/')
async def index(req):
    return redirect('/static/index.html')

@app.get('/settings')
async def get_settings(req):
    return json(clock.configuratin.settings)

@app.post('/settings')
async def post_setting(req:Request):
    settings=req.json

    state=clock.update_settings(settings)
    if isinstance(state,Exception):
        print(str(state))
        return text(str(state),500)
    
    return json(clock.configuratin.settings)

@app.get('/seconds')
async def seconds(req:Request):
    return text(str(clock.get_remain_seconds()))

@app.get('/start')
async def start(req):
    clock.running=True
    return text(str(clock.get_remain_seconds()))

@app.get('/pause')
async def pause(req):
    clock.running=False
    return text('stopped')

@app.get('/close')
def close(req):
    app.stop()

def server_start(port):
    clock.start()
    app.run(host='127.0.0.1',port=port)



if __name__ == '__main__':
    clock.debug=True
    clock.speed_radio=3
    clock.start()
    app.run(host='127.0.0.1',port=8888)